import { NextResponse } from "next/server";
import jwt from "@/utils/jwt";
import userModule from '@/modules/user'
import bcrypt from "bcryptjs";
import { AUTH_TOKEN, COOKIE_MAX_AGE } from "@/config/settings";

export async function POST(request) {
  const codeMap = {0:'账号密码验证成功，进入系统中......', 1: '用户不存在， 请先注册用户或联系超级管理员', 2:'密码错误，请重试或联系超级管理员', 3: '账号禁用中，请联系超级管理员激活'};
  const { username, password } = await request.json();
  const userInfo = await userModule.getDetailed(username);
  if (userInfo === null) return NextResponse.json({ message: 'The user does not exist', code: 1, codeMap }); 
  const isPasswordValid = await bcrypt.compare(password, userInfo.password);
  if (!isPasswordValid) return NextResponse.json({ message: 'Wrong password', code: 2, codeMap });
  const {id, nickname, avatar, mobile, email, status, roleInfo} = userInfo;
  if (userInfo.status !== 0) return NextResponse.json({ message: 'The user has been disabled', code: 3, codeMap });
  const token = await jwt.generate({id, username, status, permissions:roleInfo.permissions.map(i=>i.path) || [] });
  const response = NextResponse.json({ message: 'Success', code: 0, codeMap, userInfo: {id, username, nickname, avatar, mobile, email, roleInfo: {id: roleInfo.id,name: roleInfo.name, code: roleInfo.code,description: roleInfo.description, permissions: roleInfo.permissions}}});
  response.cookies.set(AUTH_TOKEN, token, { httpOnly: true, secure: false, maxAge: COOKIE_MAX_AGE, path: '/' });
  return response;
}